﻿var api;
var timeout;
$(document).ready(function() {

    timeout = setTimeout(function() {
        api = $.Jcrop('#cropbox', {
            onChange: cropImage,
            onSelect: cropImage,
            onFailSelect: function() { jAlert(CropSizeError); }
        });
        clearTimeout(timeout);
    }, 500);

    $("#btn-Choose-Cancel").click(function() {
        window.close();
    });

    $("#btn-Choose-Done").click(function() {
        var x, y, w, h;
        x = parseInt($("#x").val());
        y = parseInt($("#y").val());
        w = parseInt($("#w").val());
        h = parseInt($("#h").val());
        if (w == 0 || h == 0) {
            jAlert(CropError);
            return;
        }
        if (parseFloat(w) / parseFloat(h) > parseFloat(1.9)) {
            jAlert(CropRateError);
            return;
        }
        else if (parseInt(w) < 210 || parseInt(h) < 120) {
            jAlert(CropSizeError);
            return;
        }
        $("#btn-Choose-Done").parent().prepend("<img id=\"ajaxloader\" style=\"padding-top:10px;float:right;\" src=\"" + GLOBAL_RESOURCES_PATH + "/images/ajax-loader.gif\" alt=\"đang tải\" />");
        $("#btn-Choose-Done").hide();
        $("#btn-Choose-Cancel").hide();
        $.ajax({
            async: false,
            dataType: 'json',
            url: "/api/user.ashx",
            type: 'POST',
            data: {
                action: "changeAvatarByImage",
                id: $("#imageId").val(),
                x: x,
                y: y,
                w: w,
                h: h
            },
            success: function(data) {
                $("#ajaxloader").remove();
                if (data.result == "-1") {
                    window.location = "/login";
                    return;
                }
                if (data.result == "0") {
                    $("#btn-Choose-Done").show();
                    $("#btn-Choose-Cancel").show();
                    jAlert(SystemError);
                    return;
                }
                if (data.result == "2") {
                    $("#btn-Choose-Done").show();
                    $("#btn-Choose-Cancel").show();
                    jAlert(CropSizeError);
                    return;
                }
                if (data.result == "3") {
                    jAlert(CropRateError);
                    return;
                }
                if (data.result == "1") {
                    window.opener.CropAvatarPopupComplete('1');
                    window.opener.focus();
                    window.close();
                }
            }
        });
    });
});

function cropImage(coords) {
    if (parseInt(coords.w) > 0) {
        var rx = 100 / coords.w;
        var ry = 100 / coords.h;

        $('#x').val(coords.x);
        $('#y').val(coords.y);
        $('#w').val(coords.w);
        $('#h').val(coords.h);
    }
};

